//------------------------------------------------------------------ // Purpose: This program reads an ascii file and calculates the // number of words that begin with each letter of the // alphabet. All punctuation and digits are ignored. // Author: John Gauch //------------------------------------------------------------------ #include #include #include #include #include "list/list.h" using namespace std; //------------------------------------------------------------------ // Read a single word from din //------------------------------------------------------------------ bool read_word(string & word, ifstream & din) { word = ""; bool done = false; while (!din.fail() && !din.eof() && !done) { char ch; din.get(ch); if (ch >= 'a' && ch <= 'z') word = word + ch; else if (ch >= 'A' && ch <= 'Z') word = word + char(ch - 'A' + 'a'); else if (word.length() > 0) done = true; } return done; } //------------------------------------------------------------------ // Read input file and put words into 26 linked lists //------------------------------------------------------------------ void read_file(string filename, List list[]) { // Open input file ifstream din; din.open(filename.c_str()); // Read words from input file string word; while (read_word(word, din)) { // cout << word << " "; int count = 0; int index = int(word[0] - 'a'); list[index].Search(word, count); list[index].Insert(word, count + 1); } // Close input file din.close(); } //--------------------------------------------------------------------- // Process lists to get word counts //--------------------------------------------------------------------- void process_lists(List list[]) { // Print number of words in each list // and find lists with min/max words int min_list = 0; int max_list = 0; int min_count = INT_MAX; int max_count = INT_MIN; for (int i = 0; i < 26; i++) { int count = list[i].Count(); cout << char('a' + i) << " word count: " << count << endl; if (min_count > count) { min_list = i; min_count = count; } if (max_count < count) { max_list = i; max_count = count; } } // Print min/max word lists cout << "List with minimum number of words: " << char('a' + min_list) << " = " << min_count << endl; cout << "List with maximum number of words: " << char('a' + max_list) << " = " << max_count << endl; // Print selected word list string letter; cout << "Enter letter [a..z] to see list: "; cin >> letter; int index = int(letter[0] - 'a'); if ((index >= 0) && (index < 26)) list[index].Print(); } //--------------------------------------------------------------------- // Main program //--------------------------------------------------------------------- int main(int argc, char *argv[]) { // Get input file name string filename; if (argc == 2) filename = argv[1]; else { cout << "Enter name of input file: "; cin >> filename; } // Process input file to get word counts List list[26]; read_file(filename, list); process_lists(list); }